-- UISkyCityTower
-- Create By chendh Feb/22/2015
-- 天空之城试练塔页面

-- UISkyCityTower继承自Layer
UISkyCityTower = class("UISkyCityTower", function()
    return cc.Layer:create();
end);

function UISkyCityTower.create(camp)
    return UISkyCityTower.new(camp);
end

-- 内部函数声明
local offsetY = 0;
local fixWidth = 0;

local MAX_GRID_ROW    = 1;
local MIN_GRID_COLUMN = 4;

-- 构造函数
function UISkyCityTower:ctor(camp)
    -- 初始化
    self:setName("UISkyCityTower");

    -- 复用飞艇信息页面
    local node = cc.CSLoader:createNode("layout/sky_city/IslandInfo.csb");
    self:addChild(node);
    self.node = node;

    -- 阵营
    self.camp = camp;

    local bonusNode = findChildByName(self.node, "BT2/desc_node/bonus_node");
    self.scrollView = findChildByName(bonusNode, "bonus_panel");

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 标题和描述在中间浮现
    self:comformCenterEffect();

    -- 播放准心特效
    -- local reticleNode = findChildByName(self.node, "CT/reticle_node");
    playReticleEffect(self.node);

    -- 适配
    self:resize();
end

-- 分析浮岛信息
function UISkyCityTower:initData()
    -- 标题
    local title = string.format(getLocStr("tower_title"), CampM.query(self.camp, "short_name"));

    local curFloor  = SkyTowerM.getProgress(self.camp);
    local maxFloor  = SkyTowerM.getMaxFloor(self.camp);
    local iconPath  = getSkyCityPath(string.format("tower/all_tower%d", self.camp));
    local fightAbility = nil;
    local ability   = {};
    local data      = {};
    local descTitle = nil;
    local desc      = nil;

    if curFloor >= maxFloor then
        descTitle = string.format(getLocStr("tower_desc_title"), curFloor);
        desc = string.format(getLocStr("tower_desc"), CampM.query(self.camp, "short_name"));
    else

        local towerId = SkyTowerM.getTowerId(self.camp, curFloor + 1);
        local towerConfig = SkyTowerM.query(towerId);

        -- 四维信息
        ability = towerConfig["combat_dbase"];
        -- 总战力
        fightAbility = towerConfig["fight_ability"];

        local skillId = towerConfig["skills"][1];

        if skillId then
            descTitle = string.format(getLocStr("tower_desc_skill"), SkyShipSkillM.query(skillId, "name"));
            desc = SkyShipSkillM.getShipSkillDetail(skillId);
        end
    end

    data = {
        ["title"]       = title,
        ["icon"]        = iconPath,
        ["curFloor"]    = curFloor,
        ["maxFloor"]    = maxFloor,
        ["ability"]     = ability,
        ["fightAbility"] = fightAbility,
        ["descTitle"]   = descTitle,
        ["desc"]        = desc,
    };

    return data;
end

-- 适配
function UISkyCityTower:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");
    AlignM.fitToScreen(node, "bg2");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- 顶部区域至于顶部并缩放至合适大小
    local topNode = findChildByName(node, "Top");
    topNode:setVisible(true);

    AlignM.alignToTopCenter(node, "Top");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
    AlignM.alignToBottomCenter(node, "BT2");
end

function UISkyCityTower:flutterAnimation(node, name)
    -- 播放漂浮物的效果
    local parentNode = findChildByName(node, "Node_1");

    local index = 1;
    repeat
        local flutter = findChildByName(parentNode, name .. index);
        if flutter then
            local delay = math.random(0, 8);
            performWithDelay(flutter, function ()
                playFluctuateAnima(flutter, 1.5, 8);
                end, delay);
            index = index + 1;
        end
    until flutter == nil;
end

-- 重绘界面
function UISkyCityTower:redraw()
    -- 构造分析浮岛详细信息
    local data = self:initData();
    -- 上调位置节点
    local moveNodes = {};

    -- 显示标题
    local titleLabel = findChildByName(self.node, "Top/title/text");
    local skyTowerName = CampM.query(self.camp, "sky_tower_name");
    titleLabel:setString(skyTowerName);
    TextStyleM.setArtWordTitleStyle(titleLabel);

    -- 绘制图标
    local icon = findChildByName(self.node, "CT/tower_node");

    -- 修正回正中
    icon:setPositionX(0);

    local node = cc.CSLoader:createNode(string.format("layout/sky_city/background/background_tower_%d.csb", self.camp));

    self:flutterAnimation(node, "flutter");
    self:flutterAnimation(node, "dark_flutter");

    node.id = self.camp;
    node:setName("tower");
    icon:addChild(node);

    -- 重绘背景
    self:redrawTowerBg(node);

    icon:setOpacity(0);

    local delay     = cc.DelayTime:create(0.2);
    local fadeIn = cc.FadeIn:create(0.4);
    icon:runAction(cc.Sequence:create(delay, fadeIn));

    -- 四维信息
    local ability = data.ability;

    local detailNode = findChildByName(self.node, "CT/detail_node");
    -- 火力
    local attribLabel = findChildByName(detailNode, "fire_node/attrib");
    local valueLabel = findChildByName(detailNode, "fire_node/value");

    self:setSystemTextStyle(attribLabel);
    self:setSystemTextStyle(valueLabel);

    attribLabel:setString(getLocStr("airship_fire"));
    valueLabel:setString(ability.fire or getLocStr("tower_attrib_fault"));

    -- 装甲
    attribLabel = findChildByName(detailNode, "armor_node/attrib");
    valueLabel = findChildByName(detailNode, "armor_node/value");
    table.insert(moveNodes, findChildByName(detailNode, "armor_node"));

    self:setSystemTextStyle(attribLabel);
    self:setSystemTextStyle(valueLabel);

    attribLabel:setString(getLocStr("airship_armor"));
    valueLabel:setString(ability.armor or getLocStr("tower_attrib_fault"));

    -- 机动
    attribLabel = findChildByName(detailNode, "speed_node/attrib");
    valueLabel = findChildByName(detailNode, "speed_node/value");
    attribLabel.left = true;

    self:setSystemTextStyle(attribLabel);
    self:setSystemTextStyle(valueLabel);

    attribLabel:setString(getLocStr("airship_speed"));
    valueLabel:setString(ability.speed or getLocStr("tower_attrib_fault"));

    -- 幸运
    attribLabel = findChildByName(detailNode, "luck_node/attrib");
    valueLabel = findChildByName(detailNode, "luck_node/value");

    self:setSystemTextStyle(attribLabel);
    self:setSystemTextStyle(valueLabel);

    attribLabel:setString(getLocStr("airship_luck"));
    valueLabel:setString(ability.luck or getLocStr("tower_attrib_fault"));

    -- 总战力
    attribLabel = findChildByName(detailNode, "ability_node/attrib");
    valueLabel = findChildByName(detailNode, "ability_node/value");

    self:setSystemTextStyle(attribLabel);
    self:setSystemTextStyle(valueLabel);

    attribLabel:setString(getLocStr("fight_ability_2"));

    -- 逗号分段战力
    valueLabel:setString(thousandNum(data.fightAbility) or getLocStr("tower_attrib_fault"));

    -- 设置试炼层数
    local curFloor = data["curFloor"];
    attribLabel = findChildByName(detailNode, "camp_node/attrib");
    valueLabel = findChildByName(detailNode, "camp_node/value");

    self:setSystemTextStyle(attribLabel);
    self:setSystemTextStyle(valueLabel);

    attribLabel:setString(getLocStr("tower_floor"));

    local isMax = iif(curFloor < data["maxFloor"], false, true);
    local towerLayer = curFloor + 1;
    if isMax then
        towerLayer = curFloor;
    end
    local floorStr = string.format(getLocStr("sky_tower_layer"), towerLayer);
    valueLabel:setString(floorStr);

    -- 信息出现特效
    playAirShipInfoEffect(detailNode);

    -- 重绘描述
    self:redrawDesc(isMax, towerLayer);

    -- 绘制奖励
    self:redrawBonus(towerLayer, isMax);

    -- 隐藏按钮
    local btnActived = findChildByName(self.node, "BT/btn_actived");
    btnActived:setVisible(false);
end

-- 清空所有的奖励格
function UISkyCityTower:clearAllGrid()
    self.scrollView.rows = {};
    self.scrollView:removeAllChildren();
end

-- 绘制奖励
function UISkyCityTower:redrawBonus(curFloor, isMax)
    local bonusNode = findChildByName(self.node, "BT2/desc_node/bonus_node");
    bonusNode:setVisible(true);
    local panel = findChildByName(bonusNode, "bonus_panel");

    -- 收集信息
    local bonus = SkyTowerM.getCurBonus(self.camp, curFloor);

    local goodsList = {};
    if type(bonus[1]) == "number" then
        goodsList = {bonus};
    else
        goodsList = bonus;
    end

    -- 显示奖励信息
    local totalGoodsCount = #goodsList;

    if totalGoodsCount < 1 then
        return;
    end

    local totalGridCount = 4
    if totalGoodsCount > 4 then
        totalGridCount = totalGoodsCount;
    end
    -- 初始化格子
    self:initGrids(totalGridCount);

    for i = 1, totalGridCount do
        local grid          = self.scrollView:getChildByName("item" .. i);
        local goodsBg       = grid:getChildByName("bg");
        local buyImg        = grid:getChildByName("buy");
        local starNode      = grid:getChildByName("stars");
        local numLabel      = grid:getChildByName("num_label");
        local countLabel    = grid:getChildByName("num");
        local iconImg       = grid:getChildByName("icon");

        countLabel:setVisible(true);
        numLabel:setVisible(false);
        buyImg:setVisible(false);

        if i <= totalGoodsCount and type(goodsList[i]) == "table" and not isMax then
            grid:setVisible(true);

            local count   = goodsList[i][3] or 0;

            -- 显示数量
            TextStyleM.setTextStyle(countLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -2);
            if count > 1 then
                -- 需要显示数量
                countLabel:setString(changeNumType(count));
            else
                countLabel:setVisible(false);
            end

            -- 显示商品图标
            local goodsIcon;
            local para;

            local goodsIcon = self:getBonusIconPath(goodsList[i]);

            iconImg:loadTexture(goodsIcon);

            -- 注册点击事件
            self:clickShowDesc(grid, goodsList[i]);
        else
            -- 剩余的格子,bg灰色显示
            iconImg:setVisible(false);
            setGrayTransMode(goodsBg, true);
        end
    end
end

-- 注册事件处理回调函数
function UISkyCityTower:registerEventCallback()
    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            EventMgr.removeAll("UISkyCityTower");
            local uiForm = UIMgr.getCurrentScene():getFormByName("UISkyCity");
            if uiForm then
                uiForm:showInfoNode(true);
            end
        elseif eventType == "enter" then
            local uiForm = UIMgr.getCurrentScene():getFormByName("UISkyCity");
            if uiForm then
                uiForm:showInfoNode(false);
            end
        end
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UISkyCityTower", event.FOCUS_CHANGED, function(para)
        -- TODO
        if para["get"] == "UISkyCityTower" then
            local btNode = findChildByName(self.node, "BT");
            btNode:setVisible(true);

            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_AIRSHIP_SCORE, TOPMENU_FRAME_AIRSHIP_ATTRIB, TOPMENU_FRAME_HEAD_AIRSHIP);
        elseif para["lose"] == "UISkyCityTower" then
            local btNode = findChildByName(self.node, "BT");
            btNode:setVisible(false);
        end
    end);

    -- 注册试炼结果的回调
    EventMgr.register("UISkyCityTower", event.SKY_TOWER_RESULT, function(para)
        self:redraw();
        -- 关闭 "加载中" 界面
        closeCommunicatingForm();
    end);
end

-- 注册点击事件
function UISkyCityTower:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("ship_return");
            UIMgr.getCurrentScene():removeFormByName("UISkyCityTower");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));


    -- 开始试炼按钮点击事件
    local btnFight = findChildByName(self.node, "BT/btn_make");
    local function onFightClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("ship_click");
            -- 尝试开始试炼
            local ret = SkyTowerM.tryToStartFight();

            if ret == true then
                -- 显示 "加载中" 界面
                showCommunicatingForm(getLocStr("loading"));
            elseif type(ret) == "string" then
                alert(getLocStr(ret));
            end
        end
    end
    btnFight:addTouchEventListener(onFightClick);
    TextStyleM.setTextStyle(btnFight, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnFight:setTitleText(getLocStr("btn_text_start_trail"));
    btnFight:setVisible(true);
end

-- 设置信息的字体
function UISkyCityTower:setSystemTextStyle(textLabel)
    textLabel:setFontSize(TextStyleM.TEXT_SIZE_TINY + 2);
    textLabel:setTextColor(TextStyleM.TEXT_COLOR_BRIGHT_BLUE);

    textLabel:setScale(0.85);
end

-- 根据当前抽取到的类型，重绘描述信息
function UISkyCityTower:redrawDesc(isMax, curFloor)
    local descNode = findChildByName(self.node, "BT2/desc_node");
    local titleLabel = findChildByName(descNode, "title_label");
    local descLabel = findChildByName(descNode, "desc_label");

    TextStyleM.setTextStyle(titleLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED);
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, nil, nil, nil, nil, nil, nil);

    local titleName = string.format(getLocStr("tower_title"), CampM.query(self.camp, "short_name"));

    -- 层数
    local titleTempStr = getLocStr("sky_tower_desc_title");
    local title;

    title = string.format(titleTempStr, titleName, curFloor);

    local descStr = getLocStr("sky_tower_desc");

    titleLabel:setString(title);
    descLabel:setString(descStr);

    if isMax then
        -- 已达最高重新设置下
        local subheadLabel = findChildByName(self.node, "BT2/desc_node/time_label");
        local kerning = -3;
        if not isFullWidthLang() then
            kerning = -1;
        end
        TextStyleM.setTextStyle(subheadLabel, TextStyleM.TEXT_SIZE_SMALL2,
        TextStyleM.TEXT_COLOR_GRAY, false, getLocKerning() + kerning);

        local titlePosX = titleLabel:getPositionX();
        local labelWidth = titleLabel:getContentSize().width;

        local timeLPosx = titlePosX + labelWidth + 20;
        subheadLabel:setPositionX(timeLPosx);
        subheadLabel:setVisible(true);

        local arriveMax = getLocStr("arrived_max_floor");

        subheadLabel:setString(arriveMax);
    end
end

-- 初始化奖励格子
function UISkyCityTower:initGrids(gridCount)
    local w = DESIGN_WIDTH;
    local h = DESIGN_HEIGHT;

    -- 图标间距(横向)
    local wGap = -5;

    -- 图标间距(纵向)
    local hGap = 10;

    -- 图标宽度
    local iconWidth = 127;

    -- 图片高度
    local iconHeight = 110;

    local topHGap  = 10;
    local bottomHGap  = 0;
    local leftWGap = 5;

    -- 总数
    local totalCount = gridCount;

    self.scrollView.rows = {};
    self.scrollView:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/sky_city/SkyStoreItem.csb");
    -- @param windowNode    界面节点
    -- @param scrollNode    容器节点
    -- @param itemNode      单元格的节点
    -- @param totalNum      单元格总数
    -- @param maxRowNum     最大行数
    -- @param pageColNum    单页可以显示下的列数
    -- @param wGap          单元格间距(横向) 这里作为最小值使用
    -- @param hGap          单元格间距(纵向)
    -- @param iconWidth     单元格宽度
    -- @param iconHeight    单元格高度
    -- @param topHGap       上方留白
    -- @param leftWGap      左右留白  这里作为最小值使用
    -- @param touchEvent    点击事件注册函数
    -- @param initHandle    格子初始化委托
    -- @param schedulerId   定时器id
    initScrollGridsVertical(self, self.scrollView, itemNode,
        totalCount, MAX_GRID_ROW, MIN_GRID_COLUMN, wGap, hGap,
        iconWidth, iconHeight, topHGap, bottomHGap, leftWGap);

    for _, child in ipairs(self.scrollView.rows) do
        child:setScale(0.88);
    end
end

-- 获得当前奖励的iconPath
function UISkyCityTower:getBonusIconPath(bonus)
    -- 默认为item图标
    local iconPath = getItemIconPath(ItemM.query(bonus[2], "icon"));
    if bonus[1] == 1 then
        iconPath = getItemIconPath(ItemM.query(bonus[2], "icon"));
    elseif bonus[1] == 2 then
        iconPath = getLargeAttribIconPath("gem_mid");
    elseif bonus[1] == 6 then
        iconPath = getAirShipSkillIconPath(SkyShipSkillM.query(bonus[2], "icon"));
    end

    return iconPath;
end

-- 点击图标处理
function UISkyCityTower:clickShowDesc(node, bonus)
    -- 点击处理
    local bg = findChildByName(node, "bg");
    bg:setTouchEnabled(true);
    bg:addTouchEventListener(function(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
           showBonusDesc(bonus);
        end
    end);
end

-- 添加的塔只显示主塔
function UISkyCityTower:redrawTowerBg(towerNode)
    local parentNode = findChildByName(towerNode, "Node_1");
    local allChildren = parentNode:getChildren();
    local len = table.getn(allChildren);

    if len < 0 then
        return;
    end

    for i = 1, len do
        local node = allChildren[i];
        local nodeName = node:getName();
        if string.startWith(nodeName, "grass_island") or string.startWith(nodeName, "bg") then
            node:setVisible(false);
        else
            node:setVisible(true);
        end

        if string.startWith(nodeName, "dark_flutter") then
            setDarkMode(node, true);
        end
    end
end

-- 从中间浮现效果
function UISkyCityTower:comformCenterEffect()
    local TOP = findChildByName(self.node, "Top");
    local BT2  = findChildByName(self.node, "BT2");
    if not TOP then
        return;
    end

    local titleNode = findChildByName(TOP, "title");
    local descNode = findChildByName(BT2, "desc_node");

    local oldScale = titleNode:getScale();
    local descSale = descNode:getScale();

    -- title
    titleNode:setScale(oldScale * 0.8);
    local scaleUp1 = cc.EaseIn:create(cc.ScaleTo:create(0.2, oldScale * 1.05), 0.4);
    local scaleUp2 = cc.ScaleTo:create(0.05, oldScale);
    titleNode:runAction(cc.Sequence:create(scaleUp1, scaleUp2));

    descNode:setScale(descSale * 0.8);
    local scaleUp3 = cc.EaseIn:create(cc.ScaleTo:create(0.2, descSale * 1.05), 0.4);
    local scaleUp4 = cc.ScaleTo:create(0.05, descSale);
    descNode:runAction(cc.Sequence:create(scaleUp3, scaleUp4));
end